<?php
namespace App\Services;

use App\Events\ClientCidEvent;
use App\Events\MTEvent;
use App\Models\MtLogModel;
use App\Models\StoreModel;
use App\Models\UserModel;
use Framework\BaseService;
use Framework\Hope;
use Framework\Jwt;
use Framework\ModelEncryptionTrait;
use Framework\StoreCheck;
use Illuminate\Support\Facades\Hash;

class LoginService extends BaseService
{

    use ModelEncryptionTrait;
    private $jwt;

    public function __construct(Jwt $jwt)
    {
        $this->jwt = $jwt;
    }

    //常规密码登录
    public function login(string $phone, string $password, string $clientID)
    {
        if (!Hope::validatePhone($phone)) {
            $this->retError('请输入正确的手机号');
        }

        $user = UserModel::query()
            ->where('phone', $this->encryptAttribute($phone))
            ->first();

        if (empty($user)) {
            $this->retError('手机号不存在');
        }
        if (!Hash::check($password, $user->password)) {
            $this->retError('密码不正确');
        }

        $da = config('constant.login');
        //登录奖励
        event(new MTEvent($user->id, $da['value'],$da['name'] ));

        $jwt_str = $this->jwt->getToken((string)$user->id);
        //查询店铺信息

        $login_data['auth_token'] = $jwt_str;
        $login_data['user_id'] = $user->id;


        return $login_data;
    }

    //短信登录
    public function codeLogin(int $phone, int $code, string $clientID)
    {
        if (!Hope::validatePhone($phone)) {
            $this->retError('请输入正确的手机号');
        }
        $user = UserModel::query()
            ->where('phone', $this->encryptAttribute($phone))
            ->first();

        if (empty($user)) {
            $this->retError('手机号不存在');
        }
        //验证短信验证码
        app(SmsService::class)->checkSmsCode($phone, $code);
        $jwt_str = $this->jwt->getToken((string)$user->id);
        $login_data['auth_token'] = $jwt_str;
        $login_data['im_key'] = app(ImService::class)->getUserSign($user->id);

        $da = config('constant.login');
        event(new MTEvent($user->id, $da['value'],$da['name'] ));


        return $login_data;
    }


    public function wx_login($code)
    {
        https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    }


}
